package captcha

import (
	"github.com/gogf/gf/os/gcache"
	"github.com/gogf/gf/util/gconv"
	"github.com/mojocn/base64Captcha"
	"image/color"
	"time"
)

var store = base64Captcha.DefaultMemStore

const (
	Audio   = "audio"
	String  = "string"
	Math    = "math"
	Chinese = "chinese"
	width   = 110
	height  = 38
)

//Generate 创建验证码
func Generate(captchaType, sessionId string) (b64s string, err error) {
	var driver base64Captcha.Driver
	//create base64 encoding captcha
	switch captchaType {
	case "audio":
		driver = base64Captcha.NewDriverAudio(4, "en")
	case "string":
		driver = base64Captcha.NewDriverString(
			height,
			width,
			4,
			base64Captcha.OptionShowSineLine,
			4,
			base64Captcha.TxtAlphabet,
			&color.RGBA{
				R: 0,
				G: 0,
				B: 0,
				A: 0,
			},
			[]string{"wqy-microhei.ttc"},
		)
	case "math":
		driver = base64Captcha.NewDriverMath(
			height,
			width,
			0,
			0,
			&color.RGBA{
				R: 0,
				G: 0,
				B: 0,
				A: 0,
			},
			[]string{"wqy-microhei.ttc"},
		)
	case "chinese":
		driver = base64Captcha.NewDriverChinese(
			height,
			width,
			4,
			base64Captcha.OptionShowSineLine,
			2,
			base64Captcha.TxtChineseCharaters,
			&color.RGBA{
				R: 0,
				G: 0,
				B: 0,
				A: 0,
			},
			[]string{"wqy-microhei.ttc"},
		)
	default:
		driver = base64Captcha.NewDriverDigit(height, width, 4, 0.7, 80)
	}
	c := base64Captcha.NewCaptcha(driver, store)
	_, content, answer := c.Driver.GenerateIdQuestionAnswer()
	item, err := c.Driver.DrawCaptcha(content)
	if err != nil {
		return
	}
	gcache.Set("captcha_answer_"+sessionId, answer, time.Duration(1e9*60))
	b64s = item.EncodeB64string()
	return
}

//Verify 验证
func Verify(verifyValue, sessionId string) bool {
	answer := gcache.Get("captcha_answer_" + sessionId)
	return gconv.String(answer) == verifyValue
}
